from http import HTTPStatus

import pytest
from errors import Missing
from service import clients


@pytest.fixture
def client_json():
    return {
        "name": "Ivan",
        "surname": "Ivanov",
        "credit_card": "1234123412341234",
        "car_number": "A000AA98",
    }


def test_create_client_route(client, monkeypatch, client_json):
    mock_id = 123

    def mock_create_client(name, surname, credit_card, car_number):
        return {
            "id": mock_id,
            "name": name,
            "surname": surname,
            "credit_card": credit_card,
            "car_number": car_number,
        }

    monkeypatch.setattr(clients, "create_client", mock_create_client)

    response = client.post("/clients/", json=client_json)
    assert response.status_code == HTTPStatus.CREATED
    assert response.json == {"id": mock_id, **client_json}


@pytest.mark.parametrize(
    "wrong_json",
    [
        {
            "name": "Ivan",
            "surname": "Ivanov",
            "credit_card": "1234123412341234",
        },
        {
            "name": "Ivan",
            "surname": "Ivanov",
            "car_number": "A000AA98",
        },
        {
            "name": "Ivan",
            "credit_card": "1234123412341234",
            "car_number": "A000AA98",
        },
        {
            "surname": "Ivanov",
            "credit_card": "1234123412341234",
            "car_number": "A000AA98",
        },
    ],
)
def test_create_client_route_wrong_json(client, wrong_json):
    response = client.post("/clients/", json=wrong_json)
    assert response.status_code == HTTPStatus.BAD_REQUEST
    assert response.json.get("error") == "All client fields are required"


def test_get_client_route(client, monkeypatch, client_json):
    mock_id = 123

    def mock_get_client(client_id):
        return {"id": mock_id, **client_json}

    monkeypatch.setattr(clients, "get_client", mock_get_client)

    response = client.get(f"/clients/{mock_id}")
    assert response.status_code == HTTPStatus.OK
    assert response.json == {"id": mock_id, **client_json}


def test_get_client_route_wrong_id(client, monkeypatch):

    def mock_get_client(client_id):
        raise Missing(msg="not found")

    monkeypatch.setattr(clients, "get_client", mock_get_client)

    response = client.get("/clients/456")
    assert response.status_code == HTTPStatus.NOT_FOUND


def test_get_clients_list_route(client, monkeypatch, client_json):
    mock_id = 123

    def mock_get_all_clients():
        return [{"id": mock_id, **client_json}]

    monkeypatch.setattr(clients, "get_all_clients", mock_get_all_clients)

    response = client.get("/clients/")
    assert response.status_code == HTTPStatus.OK
    assert response.json == [{"id": mock_id, **client_json}]
